package wnhz.com.business.shareshop.ui;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.CompleteInfoActivity;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.groupshop.ui.MakeMerchatActivity;
import wnhz.com.business.groupshop.ui.StoreActivity;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.shareshop.bean.ShoppingCartListBean;
import wnhz.com.business.uitls.Base64Util;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyBitmapUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.uitls.imgselect.BitnapUtils;
import wnhz.com.business.uitls.imgselect.GlideImageLoader;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 申请成为商家
 */
public class MakeMerchatActivityS extends BaseActivity implements ActionBarClickListener {

    private static final int CHOSE_LOGO = 101;
    private static final int CHOSE_CARD1 = 102;
    private static final int CHOSE_CARD2 = 103;
    private static final int CHOSE_YINGYE = 104;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.ll_name)
    LinearLayout llName;
    @BindView(R.id.et_phones)
    EditText etPhones;
    @BindView(R.id.et_storename)
    EditText etStorename;
    @BindView(R.id.et_title)
    EditText et_title;
    @BindView(R.id.et_idcard)
    EditText etIdcard;
    @BindView(R.id.img_logo)
    ImageView img_logo;
    @BindView(R.id.img_id_a)
    ImageView imgIdA;
    @BindView(R.id.img_id_b)
    ImageView imgIdB;
    @BindView(R.id.img_yinye)
    ImageView img_yinye;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.fl_id_b)
    FrameLayout flIdB;

    private ImagePicker imagePicker;
    private String imglogo;
    private String img_card1;
    private String img_card2;
    private String img_yingye;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_merchats);
        ButterKnife.bind(this);

        actionbar.setData("申请成为共享商家", R.drawable.ic_lefft_white, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }

        initImgSelect();

    }
    private void initImgSelect() {
        imagePicker = ImagePicker.getInstance();

        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器

        imagePicker.setShowCamera(true);  //显示拍照按钮

        imagePicker.setCrop(true);        //允许裁剪（单选才有效）

//        imagePicker.setSaveRectangle(true); //是否按矩形区域保存

        imagePicker.setSelectLimit(1);    //选中数量限制

//        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状

        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）

        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
//
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素

        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, MakeMerchatActivityS.class);
        return intent;
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }


    @OnClick({R.id.img_logo,R.id.img_id_a, R.id.img_id_b, R.id.img_yinye, R.id.tv_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_logo:
                getImg(CHOSE_LOGO);
                break;
            case R.id.img_id_a:
                getImg(CHOSE_CARD1);
                break;
            case R.id.img_id_b:
                getImg(CHOSE_CARD2);
                break;
            case R.id.img_yinye:
                getImg(CHOSE_YINGYE);
                break;
            case R.id.tv_sign:
                if (checkInput()){
                    comit();
                }
//                //店铺
//                startActivity(StoreActivity.createIntent(this));
                break;
        }
    }

    private void comit() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("realname", etName.getText().toString().trim());
        map.put("mobile", Base64Util.encodedString2(etPhones.getText().toString().trim()));
        map.put("name", etStorename.getText().toString().trim());
        map.put("title",et_title.getText().toString().trim());
        map.put("cardId", Base64Util.encodedString2(etIdcard.getText().toString().trim()));
        map.put("0", new File(imglogo));
        map.put("1",  new File(img_card1));
        map.put("2",  new File(img_card2));
        map.put("3", new File(img_yingye));
        map.put("type", 4);
        /**
         商家申请-提交
         @param str token
         @param str realname 负责人姓名
         @param str mobile   负责人电话   （加密）
         @param str name     门店名称
         @param str title    门店简介
         @param str cardId   法人身份证号码   （加密）
         @param str logo     门店logo
         @param str card_pic 身份证照片 正反照
         @param str thumbs   营业执照或其他图片
         @param str type     1.拼团  2.返利  3.免费  4：共享商城
         @param str pid1     上级店铺id        用于返利商城 店铺返利
         @param str pid2     上上级店铺id      用于返利商城 店铺返利
         @param str pid3     上上上级 店铺id    用于返利商城 店铺返利
         */
        Set<String> set = map.keySet();
        for (String s : set) {
            Log.e("商家申请-提交参数:",s+":"+map.get(s));
        }
        XUtil.Post(Url.STORE_APPLYCONFIRM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("----商家申请-提交----", "---------------" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    if (re.equals("1")) {
                        MyToast(jsonObject.optString("info"));
                        finish();
                    }else {
                        MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(etName.getText().toString().trim())){
            MyToast("请填写用户名");
            return false;
        }
        if (TextUtils.isEmpty(etPhones.getText().toString().trim())){
            MyToast("请填写用户电话");
            return false;
        }
        if (TextUtils.isEmpty(etStorename.getText().toString().trim())){
            MyToast("请填写店铺名称");
            return false;
        }
        if (TextUtils.isEmpty(et_title.getText().toString().trim())){
            MyToast("请填写店铺简介");
            return false;
        }
        if (TextUtils.isEmpty(imglogo)){
            MyToast("请选择店铺logo");
            return false;
        }
        if (TextUtils.isEmpty(etIdcard.getText().toString())){
            MyToast("请填写法人身份证号");
            return false;
        }
        if (TextUtils.isEmpty(img_card1)||TextUtils.isEmpty(img_card2)){
            MyToast("请上传法人身份证照");
            return false;
        }
        if (TextUtils.isEmpty(img_yingye)){
            MyToast("请上传营业执照");
            return false;
        }
        return true;
    }

    private static final String compressImageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/esl/Compress/"; // 图片及其他数据保存文件夹
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {

            if (data != null) {
                switch (requestCode) {
                    case CHOSE_LOGO:
                        ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        for (int i = 0; i < images.size(); i++) {
                            imglogo = BitnapUtils.compressImage(images.get(i).path, compressImageFilePath + System.currentTimeMillis() +".jpg", 40);
                            Glide.with(MakeMerchatActivityS.this).load(imglogo).into(img_logo);
                        }
                        break;
                    case CHOSE_CARD1:
                        ArrayList<ImageItem> images2 = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        for (int i = 0; i < images2.size(); i++) {
                            img_card1 = BitnapUtils.compressImage(images2.get(i).path, compressImageFilePath + System.currentTimeMillis() + ".jpg", 40);
                            Glide.with(MakeMerchatActivityS.this).load(img_card1).into(imgIdA);
                        }
                        break;
                    case CHOSE_CARD2:
                        ArrayList<ImageItem> images3= (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        for (int i = 0; i < images3.size(); i++) {
                            img_card2 = BitnapUtils.compressImage(images3.get(i).path, compressImageFilePath + System.currentTimeMillis() + ".jpg", 40);
                            Glide.with(MakeMerchatActivityS.this).load(img_card2).into(imgIdB);
                        }
                        break;
                    case CHOSE_YINGYE:
                        ArrayList<ImageItem> images4= (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        for (int i = 0; i < images4.size(); i++) {
                            img_yingye = BitnapUtils.compressImage(images4.get(i).path, compressImageFilePath + System.currentTimeMillis() + ".jpg", 40);
                            Glide.with(MakeMerchatActivityS.this).load(img_yingye).into(img_yinye);
                        }
                        break;
                }
            }
        }
    }
    private void getImg(int code) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, 3);

        } else {
            Intent intents = new Intent(MakeMerchatActivityS.this, ImageGridActivity.class);
            startActivityForResult(intents, code);
        }
    }

}
